//
//  PersonalMessageViewController.m
//  WEIMO
//
//  Created by Lixiaoyong on 13-6-18.
//  Copyright (c) 2013年 广州从兴电子开发有限公司. All rights reserved.
//

#import "PersonalMessageViewController.h"

#import "InterfaceDefine.h"
#import "JSONKit.h"
#import "DLog.h"
#import "MyDataObject.h"
#import "UIImageView+WebCache.h"
#import "PersonalFriendListCell.h"
#import "FMManager.h"
#import "SVPullToRefresh.h"
#import "BubbleChatViewController.h"

@interface PersonalMessageViewController ()
{
    @private
    NSInteger mStartPage;
    NSInteger mPageSize;
}

/*
 value1--fromUserid,发送者id
 value2--modelsName,发送模特名称
 value3--modelsAvatarstrUrl,模特头像url
 value4--lastPostMessages,消息内容
 value5--lastSendTime,发送时间
 value6--unreadPage,未读私信条数
 */
@property (nonatomic,retain) NSMutableArray *messageLists; //<MyDataObject>
@end

@implementation PersonalMessageViewController
@synthesize messageLists;

- (void)dealloc
{
    self.messageLists = nil;
    [super dealloc];
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self)
    {
        
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [self showTabBar];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[UIBarButtonItem appearance] setTintColor:[UIColor blackColor]];
    
    self.title = @"私信";
    mStartPage = 1;
    mPageSize = 20;
    
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor colorWithRed:236.0/255 green:237.0/255 blue:241.0/255 alpha:1];
    
    [self getDatasFromFMManager];
    
    [self.tableView addPullToRefreshWithActionHandler:^{
        [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(requestPersonalMessageLists) userInfo:nil repeats:NO];
    }];
}

- (void)didReceiveMemoryWarning
{
    DEnter();
    [super didReceiveMemoryWarning];
}

#pragma mark - private methods

//显示TabBar
- (void)showTabBar
{
    if (self.tabBarController.tabBar.hidden == NO)
    {
        return;
    }
    UIView *contentView;
    if ([[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]])
        
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    
    else
        
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.frame = CGRectMake(contentView.bounds.origin.x, contentView.bounds.origin.y,  contentView.bounds.size.width, contentView.bounds.size.height - self.tabBarController.tabBar.frame.size.height);
    self.tabBarController.tabBar.hidden = NO;
    
}

//从FMManager获取数据
- (void)getDatasFromFMManager
{
    self.messageLists = [[FMManager sharedInstance] personalFriendLists];
    
    [self.tableView reloadData];
}

//请求数据
- (void)requestPersonalMessageLists
{
    NSString *userId = [[FMManager sharedInstance] userId];
    if (!userId || userId.length <= 0)
    {
        return;
    }
    
    NSString *url = [NSString stringWithFormat:@"%@/%@",kHttpHost,kQueryPFuserList];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:[NSString stringWithFormat:@"%d",mStartPage] forKey:@"startPage"];
    [dic setValue:[NSString stringWithFormat:@"%d",mPageSize] forKey:@"pageSize"];
    [dic setValue:userId forKey:@"toUserid"];
    NSString *post = [dic JSONString];
    [dic release];
    
    DLog(@"url:%@,post:%@",url,post);
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    [request appendPostData:[post dataUsingEncoding:NSUTF8StringEncoding]];
    [request setRequestMethod:@"POST"];
    [request setDelegate:self];
    [request startAsynchronous];
}

//组装数据（下拉刷新。。）
- (void)structureMessageDatasToShow:(NSMutableArray *)array
{
    if (self.messageLists == nil)
    {
        self.messageLists = [[[NSMutableArray alloc] init] autorelease];
    }
    
    for (int i=0; i<array.count; i++)
    {
        MyDataObject *item = [array objectAtIndex:i];
        [self.messageLists addObject:item];
    }
    
    [self.tableView reloadData];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.messageLists.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *personalMessageCellIdentifier = @"personalMessageCellIdentifier";
    PersonalFriendListCell *cell = [tableView dequeueReusableCellWithIdentifier:personalMessageCellIdentifier];
    if (cell == nil)
    {
        cell = [[[PersonalFriendListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:personalMessageCellIdentifier] autorelease];
    }
    
    MyDataObject *item = [self.messageLists objectAtIndex:indexPath.row];
    NSString *url = [NSString stringWithFormat:@"%@/photo/%@/%@",kHttpHost,item.value1,item.value3];
    [cell.headerImage setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"touxiang@2x.png"]];
    cell.modeName.text = item.value2;
    cell.messages.text = item.value4;
    NSString *date = item.value5;
    date = [date substringFromIndex:5];
    date = [date substringToIndex:(date.length - 3)];
    cell.dateTime.text = date;
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 61.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyDataObject *item = [self.messageLists objectAtIndex:indexPath.row];
    BubbleChatViewController *chatViewController = [[BubbleChatViewController alloc] init];
    chatViewController.toUserId = [NSString stringWithFormat:@"%@",item.value1];
    chatViewController.title = item.value2;
    NSString *imageUrl = [NSString stringWithFormat:@"%@/photo/%@/%@",kHttpHost,item.value1,item.value3];
    chatViewController.toUserImageUrl = imageUrl;
    [self.navigationController pushViewController:chatViewController animated:YES];
    [chatViewController release];
}

#pragma mark - ASIHTTPRequestDelegate

- (void)requestFailed:(ASIHTTPRequest *)request
{
    [self.tableView.pullToRefreshView stopAnimating];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSData *data = [request responseData];
    NSArray *result = [data objectFromJSONData];
    if (result.count > 0)
    {
        NSString *status = [result objectAtIndex:0];
        if ([status isEqualToString:kResponseOk])
        {
            //NSMutableArray *temp = [[[NSMutableArray alloc] init] autorelease];
            NSDictionary *dic = [result objectAtIndex:1];
            NSArray *array = [dic objectForKey:@"data"];
            
            [[FMManager sharedInstance] refreshPersonalFriendListDatas:array];
            
            [self getDatasFromFMManager];
            
            /*
            for (int i=0; i<array.count; i++)
            {
                NSDictionary *dicTemp = [array objectAtIndex:i];
                MyDataObject *item = [[MyDataObject alloc] init];
                item.value1 = [dicTemp objectForKey:@"fromUserid"];
                item.value2 = [dicTemp objectForKey:@"modelsName"];
                item.value3 = [dicTemp objectForKey:@"modelsAvatarstrUrl"];
                item.value4 = [dicTemp objectForKey:@"lastPostMessages"];
                item.value5 = [dicTemp objectForKey:@"lastSendTime"];
                item.value6 = [dicTemp objectForKey:@"unreadPage"];
                [temp addObject:item];
                [item release];
            }
             */
            
            //[self structureMessageDatasToShow:temp];
        }
    }
    
    [self.tableView.pullToRefreshView stopAnimating];
}

@end